﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.VisualBasic;
using System;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Request.Epaylinks;
using WCS.Infrastructure.Dto.Request.Log;
using WCS.Infrastructure.Dto.Request.Order;
using WCS.Infrastructure.Dto.Request.Organization;
using WCS.Infrastructure.Dto.Request.Payment;
using WCS.Infrastructure.Dto.Request.ReportForm;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Infrastructure.EFCore;
using WCS.Service.Instance;
using WCS.Service.Interface;

namespace WCS.Api.Admin.Controllers
{
    /// <summary>
    /// 支付模块
    /// </summary>
    public class PaymentController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly IPaymentService _paymentService;
        private readonly ILogService _logService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="paymentService"></param>
        /// <param name="userService"></param>
        public PaymentController(IConfiguration configuration, IPaymentService paymentService, IUserService userService, ILogService logService) : base(userService)
        {
            _configuration = configuration;
            _paymentService = paymentService;
            _logService = logService;
        }

        /// <summary>
        /// 新增交易订单【OrderAmount,CodeId,CouponInstanceId,PayMethod,RedirectUrl】(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增交易订单", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> AddOrders(OrderCreateRequestDto dto)
        {
            var result = await _paymentService.AddOrdersAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 新增订单测试数据，仅测试环境使用（不涉及真实支付）【OrderAmount,CodeId,CouponInstanceId,PayMethod】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增订单测试数据", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> AddOrdersTest(OrderCreateRequestDto dto)
        {
            var result = await _paymentService.AddOrdersTestAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 微信公众号/小程序支付(调用易票联接口)【OutTradeNo，OrderToken】
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "微信公众号/小程序支付", Group = "支付模块")]
        public async Task<IActionResult> MiniProgramPayment(MiniProgramPaymentRequestDto dto)
        {
            var result = await _paymentService.MiniProgramPaymentAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 支付结果回调(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "支付结果回调", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> ProcessPaymentResultNotification(PaymentResultNotificationRequestDto dto)
        {
            var result = await _paymentService.ProcessPaymentResultNotificationAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 主动查询支付结果（调用易票联接口-不更新订单状态）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> QueryPaymentResult(PaymentQueryRequestDto dto)
        {
            var result = await _paymentService.QueryPaymentResultAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 主动查询支付结果（调用易票联接口-更新订单状态）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "主动查询支付结果（更新订单状态）", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> ManualQueryAndUpdateOrder(PaymentQueryRequestDto dto)
        {
            var result = await _paymentService.ManualQueryAndUpdateOrder(dto);
            return Ok(result);
        }

        /// <summary>
        /// 获取交易订单记录列表（ToB）
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">每页条数</param>
        /// <param name="key">查询条件【根据订单编号】</param>
        /// <param name="storeId">门店ID</param>
        /// <param name="merchantId">商户ID</param>
        /// <param name="codeId">收款码ID</param>
        /// <param name="paymentStatus">支付状态(0=处理中，1=支付成功​，2=支付失败​​，3=已撤销，4=已关闭，5=已超时​​)</param>
        /// <param name="isDividedAgreement">是否有分账协议（null=不做筛选，false=没有分账，true=有分账）</param>
        /// <param name="beginTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        [HttpGet]
        public async Task<IActionResult> GetOrdersListToB(int page = 1, int limit = 10, string? key = "", string? storeId = "", string? merchantId = "", string? codeId = "", int paymentStatus = 1, bool? isDividedAgreement = null, DateTime? beginTime = null, DateTime? endTime = null)
        {
            var result = await _paymentService.GetOrdersListToBAsync(new OrderQueryRequestDto
            {
                Page = page,
                Limit = limit,
                Key = key,
                StoreId = storeId,
                MerchantId = merchantId,
                CodeId = codeId,
                PaymentStatus = paymentStatus,
                IsDividedAgreement = isDividedAgreement,
                BeginTime = beginTime,
                EndTime = endTime
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取消费记录列表（ToC）
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">每页条数</param>
        [HttpGet]
        public async Task<IActionResult> GetOrdersListToC(int page = 1, int limit = 10)
        {
            var result = await _paymentService.GetOrdersListToCAsync(new OrderQueryRequestDto
            {
                Page = page,
                Limit = limit,
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取消费统计数据（C端用户）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetConsumptionStatistics()
        {
            var result = await _paymentService.GetConsumptionStatistics();
            return Ok(result);
        }

        /// <summary>
        /// 获取单个交易订单详细信息
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <param name="transactionNo">商户单号</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrders(string? id = "", string? transactionNo = "")
        {
            var result = await _paymentService.GetOrdersAsync(new OrderQueryRequestDto
            {
                Id = id,
                TransactionNo = transactionNo
            });
            return Ok(result);
        }

        /// <summary>
        /// 新增结算（惠旺店手动结算）
        /// </summary>
        /// <param name="settlementTime"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [ActionLog(Action = "新增结算（惠旺店手动结算）", Group = "支付模块")]
        public async Task<IActionResult> AddSettlementRecord(DateTime settlementTime)
        {
            var result = await _paymentService.AddSettlementRecordAsync(settlementTime);
            return Ok(result);
        }

        /// <summary>
        /// 获取结算记录列表
        /// </summary>
        /// <param name="beginTime">开始日期</param>
        /// <param name="endTime">结束日期</param>
        /// <param name="merchantId">商户ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetSettlementRecordList(DateTime beginTime, DateTime endTime, string? merchantId = "")
        {
            var result = await _paymentService.GetSettlementRecordListAsync(new SettlementRecordQueryRequestDto
            {
                MerchantId = merchantId,
                BeginTime = beginTime,
                EndTime = endTime
            });
            return Ok(result);
        }

        /// <summary>
        /// 新增支付平台
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增支付平台", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> AddPaymentPlatform(PaymentPlatformCreateRequestDto dto)
        {
            var result = await _paymentService.AddPaymentPlatformAsync(dto);
            return Ok(result);
        }


        /// <summary>
        /// 获取支付平台列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetPaymentPlatformList(int page = 1, int limit = 10, string? key = "")
        {
            var result = await _paymentService.GetPaymentPlatformListAsync(new PaymentPlatformQueryRequestDto
            {
                Page = page,
                Limit = limit,
                Key = key
            });
            return Ok(result);
        }


        /// <summary>
        /// 费率计算
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> CalculateRate(SplitWithdrawalRequestDto dto)
        {
            var result = await _paymentService.CalculateRateAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 分账并提现(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增分账并提现记录", Group = "支付模块")]
        //[AllowAnonymous]
        public async Task<IActionResult> SplitWithdrawal(SplitWithdrawalRequestDto dto)
        {
            var result = await _paymentService.SplitWithdrawalAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 平台方分账提现
        /// </summary>
        /// <param name="amount"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增平台方分账提现记录", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> PlatformSplitWithdrawal(long amount)
        {
            var result = await _paymentService.PlatformSplitWithdrawalAsync(amount);
            return Ok(result);
        }

        /// <summary>
        /// 分账结果回调通知(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "分账结果回调通知", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> HandleMerchantSplitResultNotification(SplitResultNotificationRequest dto)
        {
            var result = await _paymentService.HandleMerchantSplitResultNotificationAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 商户分账结果查询(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "商户分账结果查询", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> MerchantSplitResultQuery(SplitResultQueryRequestDto dto)
        {
            var result = await _paymentService.MerchantSplitResultQueryAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 新增分账商户提现记录（平台接口）
        /// </summary>
        /// <param name="epaylinksSplitRecordId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionLog(Action = "新增分账商户提现记录", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> AddSubMerchantWithdrawalRecord(string epaylinksSplitRecordId)
        {
            var result = await _paymentService.AddSubMerchantWithdrawalRecordAsync(new AddWithdrawalRequest 
            {
                EpaylinksSplitRecordId = epaylinksSplitRecordId
            });
            return Ok(result);
        }

        /// <summary>
        /// 分账商户提现结果回调通知(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "分账商户提现结果回调通知", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> HandleSubMerchantWithdrawalResultNotification(SubMerchantWithdrawalResultNotificationRequestDto dto)
        {
            var result = await _paymentService.HandleSubMerchantWithdrawalResultNotificationAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 分账商户提现结果查询(调用易票联接口)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "分账商户提现结果查询", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> SubMerchantWithdrawalResultQuery(SubMerchantWithdrawalResultQueryRequestDto dto)
        {
            var result = await _paymentService.SubMerchantWithdrawalResultQueryAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 获取用户提现记录列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetWithdrawalRecordList(int page = 1, int limit = 10)
        {
            var result = await _paymentService.GetWithdrawalRecordListAsync(new Infrastructure.Dto.Common.BaseRequestDto
            {
                Page = page,
                Limit = limit
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取单个提现记录详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetWithdrawalRecordDetailAsync(string id)
        {
            var result = await _paymentService.GetWithdrawalRecordDetailAsync(id);
            return Ok(result);
        }

        /// <summary>
        /// 新增订单退款记录（调用易票联接口）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "新增订单退款记录", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> AddOrderRefundRecord(AddOrderRefundRecordRequestDto dto)
        {
            var result = await _paymentService.AddOrderRefundRecordAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 订单退款结果回调通知（调用易票联接口）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "订单退款结果回调通知", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> HandleOrderRefundResultNotification(RefundResultNotificationRequestDto dto)
        {
            var result = await _paymentService.HandleOrderRefundResultNotificationAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 订单退款结果查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionLog(Action = "订单退款结果查询", Group = "支付模块")]
        [AllowAnonymous]
        public async Task<IActionResult> OrderRefundRecordQuery(RefundResultQueryRequestDto dto)
        {
            var result = await _paymentService.OrderRefundRecordQueryAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// 获取订单退款记录列表
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrderRefundRecordList(string orderId)
        {
            var result = await _paymentService.GetOrderRefundRecordListAsync(orderId);
            return Ok(result);
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="reportFormType">报表类型 0=日报表 1=周报表 2=月报表</param>
        /// <param name="selectDateTime">查询日期时间</param>
        /// <param name="merchantId">商户ID</param>
        /// <param name="storeId">门店ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetReportForm(int reportFormType = 0, DateTime? selectDateTime = null, string? merchantId = "", string? storeId = "")
        {
            var result = await _paymentService.GetReportFormAsync(new ReportFormRequestDto
            {
                ReportFormType = reportFormType,
                SelectDateTime = (DateTime)selectDateTime,
                MerchantId = merchantId,
                StoreId = storeId
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取收款记录
        /// </summary>
        /// <param name="beginTime">开始日期</param>
        /// <param name="endTime">结束日期</param>
        /// <param name="merchantId">商户ID</param>
        /// <param name="storeId">门店ID</param>
        /// <param name="codeId">收款码ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetCollectionRecordList(DateTime beginTime, DateTime endTime, string? merchantId = "", string? storeId = "", string? codeId = "")
        {
            var result = await _paymentService.GetCollectionRecordListAsync(new ReportFormRequestDto
            {
                BeginTime = beginTime,
                EndTime = endTime,
                MerchantId = merchantId,
                StoreId = storeId,
                CodeId = codeId
            });
            return Ok(result);
        }

        /// <summary>
        /// 获取今日营业额
        /// </summary>
        /// <param name="merchantId"></param>
        /// <param name="storeId"></param>
        /// <param name="codeId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetTodayTurnover(string? merchantId = "", string? storeId = "", string? codeId = "")
        {
            var result = await _paymentService.GetTodayTurnoverAsync(new TodayTurnoverRequestDto
            {
                MerchantId = merchantId,
                StoreId = storeId,
                CodeId = codeId
            });

            return Ok(result);
        }

        /// <summary>
        /// 获取平台首页数据
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetPlatformHomepage(DateTime dateTime)
        {
            var result = await _paymentService.GetPlatformHomepageAsync(dateTime);
            return Ok(result);
        }
    }
}
